﻿using Microsoft.Extensions.Configuration;
using System;
using System.Collections.Generic;
using System.Drawing;
using System.Text;
using BarcodeLib;
using BarcodeStandard;
using System.IO;

namespace ServiceCore.Tool.Barcode
{
    public interface IBarcode_Service
    {
        string GenerateBarCodeBitmap(string content);
    }
    public class Barcode_Service : IBarcode_Service
    {
        private readonly IConfiguration AppSettingConfig;
        public Barcode_Service(IConfiguration configuration)
        {
            AppSettingConfig = configuration;
        }

        /// <summary>
        /// 生成条形码
        /// </summary>
        /// <param name="content">内容</param>
        /// <returns></returns>
        public string GenerateBarCodeBitmap(string content)
        {
            using (var barcode = new BarcodeLib.Barcode()
            {
                IncludeLabel = true,
                Alignment = AlignmentPositions.CENTER,
                //Width = 400,
                Height = 80,
                RotateFlipType = RotateFlipType.RotateNoneFlipNone,
                BackColor = Color.White,
                ForeColor = Color.Black,
                LabelPosition = LabelPositions.BOTTOMCENTER,
                BarWidth = 2,
                LabelFont = new Font("微软雅黑", 15, FontStyle.Bold),
                ImageFormat = System.Drawing.Imaging.ImageFormat.Png
            })
            {
                Image image = barcode.Encode(TYPE.CODE128A, content);

                MemoryStream ms = new MemoryStream();
                image.Save(ms, System.Drawing.Imaging.ImageFormat.Png);
                byte[] arr = new byte[ms.Length];
                ms.Position = 0;
                ms.Read(arr, 0, (int)ms.Length);
                ms.Close();
                return "data:image/png;base64," + Convert.ToBase64String(arr);
            }
        }
        private Bitmap GetImageFromBase64(string base64string)
        {
            byte[] b = Convert.FromBase64String(base64string);
            MemoryStream ms = new MemoryStream(b);
            Bitmap bitmap = new Bitmap(ms);
            return bitmap;
        }
    }
}
